package perso.marcr.lst.util;

import java.io.File;
import java.io.IOException;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

import org.springframework.oxm.XmlMappingException;

public class Xml {

	/**
	 * @param entity
	 * @param clazz
	 * @param szFile
	 * @throws JAXBException
	 * @throws XmlMappingException
	 * @throws IOException
	 */
	public static void save(Object entity, Class<?> clazz, String szFile) throws JAXBException, XmlMappingException, IOException
	{
		JAXBContext jaxbContext = JAXBContext.newInstance(clazz);

		Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
		jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, new Boolean(true));

		File file = new File(szFile);
		jaxbMarshaller.marshal(entity, file);
	}

	/**
	 * @param clazz
	 * @param szFile
	 * @return
	 * @throws JAXBException
	 */
	public static Object read(Class<?> clazz, String szFile) throws JAXBException
	{
		JAXBContext jc = JAXBContext.newInstance(clazz);
		Unmarshaller u = jc.createUnmarshaller();

		File file = new File(szFile);

		return u.unmarshal(file);
	}
}
